<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="120px">
            <el-form-item label="描述" prop="description">
              <el-input v-model="queryParams.description" clearable placeholder="请输入描述" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="queryParams.sort" clearable placeholder="请输入排序" @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
            <!--              <el-input v-model="queryParams.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="读写器编码" prop="readerCode">
              <el-input v-model="queryParams.readerCode" clearable placeholder="请输入读写器编码" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="读写器名称" prop="readerName">
              <el-input v-model="queryParams.readerName" clearable placeholder="请输入读写器名称" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="queryParams.ipAddress" clearable placeholder="请输入IP地址" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="MAC地址" prop="macAddress">
              <el-input v-model="queryParams.macAddress" clearable placeholder="请输入MAC地址" @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="关联工位ID" prop="workstationId">
              <el-input v-model="queryParams.workstationId" clearable placeholder="请输入关联工位ID" @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="工位" prop="workstationId">
              <el-select
                v-model="queryParams.workstationId"
                :loading="workstationLoading"
                :remote-method="handleWorkstationSearch"
                clearable
                filterable
                placeholder="请选择工位"
                remote
              >
                <el-option v-for="item in workstationOptions" :key="item.id" :label="item.workstationName" :value="item.id">
                  <span>{{ item.workstationName }}</span>
                  <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="最后心跳时间" prop="lastHeartbeatTime">
              <el-date-picker
                v-model="queryParams.lastHeartbeatTime"
                clearable
                placeholder="请选择最后心跳时间"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidReader:add']" icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidReader:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidReader:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidReader:export']" icon="Download" plain type="warning" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="rfidReaderList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column v-if="true" align="center" label="主键ID" prop="id" />
        <el-table-column align="center" label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description" />
        <el-table-column align="center" label="排序" prop="sort" />
        <!--        <el-table-column label="是否删除：0-未删除，1-已删除" align="center" prop="isDeleted" />-->
        <el-table-column align="center" label="读写器编码" prop="readerCode" />
        <el-table-column align="center" label="读写器名称" prop="readerName" />
        <el-table-column align="center" label="读写器类型" prop="readerType" />
        <el-table-column align="center" label="IP地址" prop="ipAddress" />
        <el-table-column align="center" label="MAC地址" prop="macAddress" />
        <!-- <el-table-column align="center" label="关联工位ID" prop="workstationId" /> -->
        <el-table-column align="center" label="关联工位名称" prop="workstationName" />
        <el-table-column align="center" label="在线状态" prop="active">
          <template #default="scope">
            <el-tag :type="scope.row.active === 1 ? 'success' : 'danger'">
              {{ scope.row.active === 1 ? '在线' : '不在线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后心跳时间" prop="lastHeartbeatTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastHeartbeatTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" min-width="105">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['painting:rfidReader:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="scope.row.status === 1 ? '禁用' : '启用'" placement="top">
              <el-button
                v-hasPermi="['painting:rfidReader:edit']"
                :icon="scope.row.status === 1 ? 'CircleClose' : 'CircleCheck'"
                :type="scope.row.status === 1 ? 'danger' : 'success'"
                link
                @click="handleStatusChange(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['painting:rfidReader:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改RFID读写器管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="800px">
      <el-card class="mb-4" shadow="never">
        <template #header>
          <div class="card-header">
            <span>在线读写器列表</span>
          </div>
        </template>
        <el-table v-loading="onlineReaderLoading" :data="onlineReaderList" @row-click="handleOnlineReaderSelect">
          <el-table-column label="读写器编码" prop="readerCode" />
          <el-table-column label="读写器名称" prop="name" />
          <el-table-column label="IP地址" prop="ipAddress" />
          <el-table-column label="MAC地址" prop="macAddress" />
          <el-table-column label="最后心跳时间" prop="lastReadTime" width="180">
            <template #default="scope">
              <!--  321            -->
              <span>{{ parseTime(scope.row.lastReadTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-form ref="rfidReaderFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入内容" type="textarea" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="读写器编码" prop="readerCode">
          <el-input v-model="form.readerCode" placeholder="请输入读写器编码" />
        </el-form-item>
        <el-form-item label="读写器名称" prop="readerName">
          <el-input v-model="form.readerName" placeholder="请输入读写器名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress">
          <el-input v-model="form.macAddress" placeholder="请输入MAC地址" />
        </el-form-item>
        <!-- 是否启用 -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联工位" prop="workstationId">
          <el-select
            v-model="form.workstationId"
            :loading="workstationLoading"
            :remote-method="handleWorkstationSearch"
            clearable
            filterable
            placeholder="请选择关联工位"
            remote
          >
            <el-option v-for="item in workstationOptions" :key="item.id" :label="item.workstationName" :value="item.id">
              <span>{{ item.workstationName }}</span>
              <span class="text-gray-500 ml-2">({{ item.workstationCode }})</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="最后心跳时间" prop="lastHeartbeatTime">
          <el-date-picker clearable
            v-model="form.lastHeartbeatTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择最后心跳时间">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="RfidReader" setup>
import { addRfidReader, delRfidReader, getRfidReader, listRfidReader, updateRfidReader } from '@/api/painting/rfidReader';
import { RfidReaderForm, RfidReaderQuery, RfidReaderVO } from '@/api/painting/rfidReader/types';
import { getOnlineReaderList } from '@/api/painting/reader';
import { listWorkstation } from '@/api/painting/workstation';
import { WorkstationVO } from '@/api/painting/workstation/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const rfidReaderList = ref<RfidReaderVO[]>([]);
const onlineReaderList = ref<any[]>([]);
const onlineReaderLoading = ref(false);
const workstationOptions = ref<WorkstationVO[]>([]);
const workstationLoading = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const refreshTimer = ref<number | null>(null);

const queryFormRef = ref<ElFormInstance>();
const rfidReaderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RfidReaderForm = {
  id: undefined,
  status: undefined,
  description: undefined,
  sort: undefined,
  isDeleted: undefined,
  readerCode: undefined,
  readerName: undefined,
  readerType: undefined,
  ipAddress: undefined,
  macAddress: undefined,
  workstationId: undefined,
  lastHeartbeatTime: undefined
};
const data = reactive<PageData<RfidReaderForm, RfidReaderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    description: undefined,
    sort: undefined,
    isDeleted: undefined,
    readerCode: undefined,
    readerName: undefined,
    readerType: undefined,
    ipAddress: undefined,
    macAddress: undefined,
    workstationId: undefined,
    lastHeartbeatTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态：0-禁用，1-启用不能为空', trigger: 'change' }],
    isDeleted: [{ required: true, message: '是否删除：0-未删除，1-已删除不能为空', trigger: 'blur' }],
    readerCode: [{ required: true, message: '读写器编码不能为空', trigger: 'blur' }],
    readerName: [{ required: true, message: '读写器名称不能为空', trigger: 'blur' }],
    readerType: [{ required: true, message: '读写器类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询RFID读写器管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRfidReader(queryParams.value);
  rfidReaderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  stopRefreshTimer();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  rfidReaderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RfidReaderVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 获取在线读写器列表 */
const getOnlineReaderListData = async () => {
  onlineReaderLoading.value = true;
  try {
    const res = await getOnlineReaderList();
    onlineReaderList.value = res.data;
  } finally {
    onlineReaderLoading.value = false;
  }
};

/** 开始定时刷新在线读写器列表 */
const startRefreshTimer = () => {
  // 清除已存在的定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
  // 设置新的定时器，每5秒刷新一次 暂不启用定时刷新
  // refreshTimer.value = window.setInterval(() => {
  //   getOnlineReaderListData();
  // }, 5000);
};

/** 停止定时刷新 */
const stopRefreshTimer = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
};

/** 处理在线读写器选择 */
const handleOnlineReaderSelect = (row: any) => {
  form.value.readerCode = row.readerCode;
  form.value.readerName = row.name;
  form.value.ipAddress = row.ipAddress;
  form.value.macAddress = row.macAddress;
  form.value.lastHeartbeatTime = row.lastReadTime;
};

/** 处理工位搜索 */
const handleWorkstationSearch = async (query: string) => {
  workstationLoading.value = true;
  try {
    const res = await listWorkstation({
      workstationName: query,
      pageSize: 10,
      pageNum: 1
    });
    workstationOptions.value = res.rows;
  } finally {
    workstationLoading.value = false;
  }
};

/** 获取工位详情 */
const getWorkstationDetail = async (id: string | number) => {
  if (!id) return;
  workstationLoading.value = true;
  try {
    const res = await listWorkstation({
      id: id,
      pageSize: 1,
      pageNum: 1
    });
    if (res.rows.length > 0) {
      workstationOptions.value = res.rows;
    }
  } finally {
    workstationLoading.value = false;
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getOnlineReaderListData();
  startRefreshTimer();
  dialog.visible = true;
  dialog.title = '添加RFID读写器管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RfidReaderVO) => {
  reset();
  getOnlineReaderListData();
  startRefreshTimer();
  const _id = row?.id || ids.value[0];
  const res = await getRfidReader(_id);
  Object.assign(form.value, res.data);
  // 获取工位详情用于回显
  if (form.value.workstationId) {
    await getWorkstationDetail(form.value.workstationId);
  }
  dialog.visible = true;
  dialog.title = '修改RFID读写器管理';
};

/** 提交按钮 */
const submitForm = () => {
  rfidReaderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRfidReader(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRfidReader(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RfidReaderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除RFID读写器管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delRfidReader(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'painting/rfidReader/export',
    {
      ...queryParams.value
    },
    `rfidReader_${new Date().getTime()}.xlsx`
  );
};

/** 修改状态 */
const handleStatusChange = async (row: RfidReaderVO) => {
  const text = row.status === 1 ? '禁用' : '启用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.readerName + '"吗？');
    const newStatus = row.status === 1 ? 0 : 1;
    await updateRfidReader({
      ...row,
      status: newStatus
    });
    proxy?.$modal.msgSuccess(text + '成功');
    await getList();
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getList();
});

onUnmounted(() => {
  stopRefreshTimer();
});
</script>
